<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script src="/socket.io/socket.io.js"></script>

<body>
    <div>username:<input type='text' id='username'></div>
    <div>password:<input type='password' id='password'></div>
    <button id='login'>login</button>
    <button id='testBtn'>testBtn</button>
    <script>
        // socket = io();
        let socket;
        let loginBtn = document.querySelector('#login');
        loginBtn.addEventListener('click', function() {
            const inputUsername = document.querySelector('#username').value;
            const inputPassword = document.querySelector('#password').value;

            socket = io({
                query: {
                    name: inputUsername,
                    password: inputPassword
                },
                reconnection: false,
            });
            // 连接事件
            socket.on('connect', () => {
                console.info('connect');
                socket.emit('sendMessage', 'csy sb');
            });
            // 连接错误
            socket.on('connect_error', (err) => {
                if (err && err.message === 'INVALID_USERNAME' || err.message === 'INVALID_PASSWORD') {
                    alert('认证失败');
                    return;
                }
            });
            // 断开连接
            socket.on('disconnect', () => {
                console.info('disconnect');
            });

            // 
            socket.on('online', (userList) => {
                console.info(`userList:${userList}`);
            });

            //
            socket.on('receieveMessage', (message) => {
                console.log(message);
            });
        });


        testBtn.onclick = function() {
            socket.emit('sendMessage', 'haha');
            fetch('/history').then(res => res.json()).then((history) => {
                console.log('history', history);
            })
        };
    </script>
</body>

</html>